package com.xd.pre.modules.security.ldap.userdetails;

import cn.hutool.core.collection.CollUtil;
import com.xd.pre.modules.sys.domain.SysUser;
import com.xd.pre.modules.sys.service.ISysUserService;
import org.springframework.ldap.core.ContextSource;
import org.springframework.ldap.core.DirContextOperations;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.ldap.userdetails.DefaultLdapAuthoritiesPopulator;

import java.util.Collection;
import java.util.List;
import java.util.Set;

/**
 * 这个类给LDAP用户添加数据库中的角色
 * @author tangkaifei
 */
public class PreLdapAuthoritiesPopulator extends DefaultLdapAuthoritiesPopulator {
    private ISysUserService sysUserService;
    /**
     * Constructor for group search scenarios. <tt>userRoleAttributes</tt> may still be
     * set as a property.
     *
     * @param contextSource   supplies the contexts used to search for user roles.
     * @param groupSearchBase if this is an empty string the search will be performed from
     */
    public PreLdapAuthoritiesPopulator(ContextSource contextSource, String groupSearchBase) {
        super(contextSource, groupSearchBase);
    }

    @Override
    protected Set<GrantedAuthority> getAdditionalRoles(DirContextOperations user,
                                                       String username) {
        SysUser sysUser = sysUserService.findByUserInfoName(username);

        // 获取用户拥有的角色
        // 用户权限列表，根据用户拥有的权限标识与如 @PreAuthorize("hasAuthority('sys:menu:view')") 标注的接口对比，决定是否可以调用接口
        // 权限集合
        Integer userId = sysUser.getUserId();
        Set<String> permissions = sysUserService.findPermsByUserId(userId);
        // 角色集合
        Set<String> roleIds = sysUserService.findRoleIdByUserId(userId);
        permissions.addAll(roleIds);
        List<GrantedAuthority> authorityList = AuthorityUtils.createAuthorityList(permissions.toArray(new String[0]));
        return CollUtil.newHashSet(authorityList);
    }
}
